package com.mamingchao.concurrent.Lock.volatile_test.v1;

import java.util.concurrent.TimeUnit;

/**
 * 演示 valatile 是线程之间使变量可见
 * Created by mamingchao on 2020/10/27.
 */
public class Main {
    /*volatile*/ boolean running = true;

    void m(){
        System.out.println("start method m");
        while(running) {
            //这个地方 有内容的，注释打开，不加volatile 线程之间也能看见 running 变量，这个是为什么呢？
//            System.out.println("I am running");
//            try {
//                TimeUnit.MILLISECONDS.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
        System.out.println("end method m");
    }

    public static void main(String[] args) {
        Main t = new Main();

        /*
         * :: 点过去，就是Runnable 接口
         * 这里的意思就是 new Thread(new Runnable(){m()})
         */
        new Thread(t::m).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t.running = false;
    }
}
